package br.com.ianalise.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.rmi.registry.Registry;
import java.security.CodeSource;
import java.security.ProtectionDomain;

import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import br.com.ianalise.negocio.excecoes.IAnaliseException;
import br.com.ianalise.negocio.fachada.Fachada;
import br.com.ianalise.negocio.pojo.ConfigRede;
import br.com.ianalise.outros.ThreadServer;
import br.com.ianalise.outros.pegarIP;

public class ConfiguracoesRede extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8677750452144886608L;
	private JPanel contentPane;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JTextField textFieldIpServidor;
	private JButton btnFechar;
	private String tempIPServidor;
	private JLabel lblIpMaquina;
	private JLabel lblIp;
	private JRadioButton rdbtnCliente;
	private JRadioButton rdbtnServidor;
	private JTextArea textArea;
	private JSpinner spinner;
	protected Registry registry;
	protected ThreadServer threadServer;
	private JButton btnAplicar;


	/**
	 * Create the frame.
	 */
	public ConfiguracoesRede(final String titulo, String subTitulo) throws IAnaliseException {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				btnFechar.doClick();
			}
		});
		setModal(true);
		this.setSize(400, 340);
		this.setLocationRelativeTo(null);
		setResizable(false);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		this.setTitle(titulo + " - " + subTitulo);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		tempIPServidor = "";		
		
		
		/*
		 * Quando apetar ESC em qualquer lugar do contentPane executar o botão cancelar
		 */
		contentPane.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), "CANCELAR");
		contentPane.getActionMap().put("CANCELAR", new AbstractAction() {
			private static final long serialVersionUID = -4318457033998934089L;

			public void actionPerformed(ActionEvent e) {
				btnFechar.doClick();
			}
		});
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setBorder(new TitledBorder(null, " Configura\u00E7\u00F5es de Rede ", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		rdbtnServidor = new JRadioButton("Servidor");
		rdbtnServidor.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tempIPServidor = textFieldIpServidor.getText();
				textFieldIpServidor.setEnabled(false);
				textFieldIpServidor.setText(pegarIP.localhost());
			}
		});
		buttonGroup.add(rdbtnServidor);
		
		rdbtnCliente = new JRadioButton("Cliente");
		rdbtnCliente.setSelected(true);
		rdbtnCliente.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textFieldIpServidor.setEnabled(true);
				textFieldIpServidor.setText(tempIPServidor);
			}
		});
		buttonGroup.add(rdbtnCliente);
		
		lblIpMaquina = new JLabel("IP Máquina:");
		lblIp = new JLabel();
		lblIp.setText(pegarIP.localhost());
		
		JLabel lblIpServidor = new JLabel("IP Servidor:");
		
		textFieldIpServidor = new JTextField();
		textFieldIpServidor.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				if(textFieldIpServidor.getText().equals(lblIp.getText())) {
					rdbtnServidor.setSelected(true);
				}
			}
		});
		textFieldIpServidor.setColumns(10);
		
		JLabel lblPorta = new JLabel("Porta:");
		
		spinner = new JSpinner();
		spinner.setModel(new SpinnerNumberModel(1099, 1099, 65535, 1));
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(rdbtnServidor)
							.addGap(18)
							.addComponent(rdbtnCliente))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblIpMaquina)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(lblIp))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblIpServidor)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(textFieldIpServidor, GroupLayout.PREFERRED_SIZE, 128, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblPorta)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(spinner, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap(545, Short.MAX_VALUE))
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(rdbtnServidor)
						.addComponent(rdbtnCliente))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblIpMaquina)
						.addComponent(lblIp))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblIpServidor)
						.addComponent(textFieldIpServidor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblPorta)
						.addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		panel_1.setLayout(gl_panel_1);
		
		JPanel panel_3 = new JPanel();
		panel.add(panel_3, BorderLayout.SOUTH);
		
		btnFechar = new JButton("Fechar (ESC)");
		btnFechar.setMnemonic(KeyEvent.VK_F);
		btnFechar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/*int opcao = JOptionPane.showOptionDialog(null,
                        "Deseja realmente cancelar as alterações na configuração do sistema?",
                        titulo, JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
				
				if (opcao == 0) { // se desejar cadastrar
					dispose();
				}
			}*/
				dispose();
			}
		});
		panel_3.add(btnFechar);
		
		btnAplicar = new JButton("Aplicar (F2)");
		btnAplicar.setMnemonic(KeyEvent.VK_I);
		btnAplicar.addActionListener(new ActionListener() {
			private String comando;

			public void actionPerformed(ActionEvent e) {
			
				int opcao = JOptionPane.showOptionDialog(null,
                        "Deseja realmente alterar as configurações de rede?\n\nISSO PODE AFETAR O FUNCIONAMENTO DO PROGRAMA!",
                        titulo, JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
				
				if (opcao == 0) { // se desejar cadastrar
					
					ConfigRede configRede = new ConfigRede();
					if(rdbtnServidor.isSelected()) {
						configRede.setTipoNo("servidor");
						configRede.setIpServidor("");
					} else {
						configRede.setTipoNo("cliente");
						configRede.setIpServidor(textFieldIpServidor.getText());
					}
					
					configRede.setPorta(spinner.getValue().toString());
					
					boolean alterou = false;
					try {
						alterou = Fachada.getInstancia().alterarConfigRede(configRede);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						try {
							throw new IAnaliseException(e.toString());
						} catch (IAnaliseException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}
					}
					
					if(alterou) {
						JOptionPane.showMessageDialog(
			                    null,
			                    "O sistema será reiniciado automaticamente para que as alterações tenham efeito.",
			                    titulo+" - Informação",
			                    JOptionPane.INFORMATION_MESSAGE,
			                    null);
					} else {
						JOptionPane.showMessageDialog(
			                    null,
			                    "As modificações nas configurações de rede não poderam ser realizadas!",
			                    titulo+" - Erro",
			                    JOptionPane.ERROR_MESSAGE,
			                    null);
					}
					
					//JOptionPane.showMessageDialog(null, "O sistema será reiniciado automaticamente para que as alterações tenham efeito.", titulo, JOptionPane.INFORMATION_MESSAGE);
					
					/*
					 * Reiniciando a aplicação
					 */
					Class<TelaPrincipal> cls = TelaPrincipal.class;  
					ProtectionDomain pDomain = cls.getProtectionDomain();  
					CodeSource cSource = pDomain.getCodeSource();  
					URL loc = cSource.getLocation();  
					String[] nomeAplicacao = loc.toString().substring(5).split("/");
				
					comando = "java -jar " + nomeAplicacao[nomeAplicacao.length-1];  
					   
					try {  
						@SuppressWarnings("unused")
						Process Processo = Runtime.getRuntime().exec(comando); 
					} catch (IOException MensagemdeErro) {  
						System.out.println(MensagemdeErro);  
					}
					System.exit(0); //fechando a aplicação
					
					/*
					 * Fim do reinicio....
					 */
					
					
					
					/*threadServer = ThreadServer.getInstancia(spinner.getValue().toString());
	
					if(threadServer != null && threadServer.getState().toString().equals("NEW")) {
	
						threadServer.start();
						
						//esperando o status ser atualizado
						while(threadServer.getStatus() == null) {
							System.out.print("PORRA");
						}
						System.out.println();
						if(textArea.getText().equals("")) {
							textArea.setText(threadServer.getStatus());
						} else {
							textArea.setText(textArea.getText()+"\n"+threadServer.getStatus());
						}
						
						if(threadServer.getServidorLigado()) {
							btnParar.setEnabled(true);
							btnAplicar.setEnabled(false);
						}
					}*/
				}
			}
		});
		panel_3.add(btnAplicar);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new TitledBorder(null, " Status ", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel_2.add(scrollPane, BorderLayout.CENTER);
		
		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setLineWrap(true);
		scrollPane.setViewportView(textArea);
		
		
		
		/*
		 * Isso tem que vim depois de tudo!
		 */
		ConfigRede configRede = Fachada.getInstancia().consultarConfig();
		
		if(configRede.getTipoNo().equals("servidor")){
			rdbtnCliente.setSelected(false);
			rdbtnServidor.setSelected(true);
			textFieldIpServidor.setText(pegarIP.localhost());
			textFieldIpServidor.setEnabled(false);
			spinner.setValue(Integer.parseInt(configRede.getPorta()));
		} else {
			rdbtnServidor.setSelected(false);
			rdbtnCliente.setSelected(true);
			textFieldIpServidor.setText(configRede.getIpServidor());
			spinner.setValue(Integer.parseInt(configRede.getPorta()));
		}
	}
}
